import XLSX from 'xlsx'
import html2canvas from 'html2canvas'
export function json2xlsx<T>(data: T[], fileName: string, sheetName: string) {
  const jsonWorkSheet = XLSX.utils.json_to_sheet(data)
  const workBook = {
    SheetNames: [sheetName], // 指定有序 sheet 的 name
    Sheets: {
      [sheetName]: jsonWorkSheet // 表格数据内容
    }
  }
  return XLSX.writeFile(workBook, fileName.indexOf('.') === -1 ? fileName + '.xlsx' : fileName)
}

export async function readBuffer(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = loadEvent => resolve(loadEvent.target?.result)
    reader.onerror = e => reject(e)
    reader.readAsArrayBuffer(file)
  })
}

export function getExtend(name: string) {
  const dot = name.lastIndexOf('.')
  return name.substring(dot + 1)
}
export function generateFileName(prefix: string, ext: string) {
  return prefix + new Date().toLocaleString().replaceAll(/(\/)|(:)/g, '-') + '.' + ext
}

export function dataURLtoFile(dataUrl: string, fileName: string) {
  const arr = dataUrl.split(',')
  const mime = arr[0].match(/:(.*?);/)![1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

export function exportScreenshot(dom: HTMLElement, filename: string) {
  const { width, height } = dom.getBoundingClientRect()
  html2canvas(dom, {
    width,
    height,
    // 开启跨域配置
    useCORS: true,
    allowTaint: true
  }).then(async canvas => {
    const src = canvas.toDataURL('image/jpeg', 1.0)
    // 发送文件到后端
    // const image_file = dataURLtoFile(src, filename)
    // const fd = new FormData()
    // fd.append('id', 'nameplate_' + this.meter_no)
    // fd.append('file', filename)
    // fd.append('file', image_file)
    // await UploadFileByID(fd)
    // // 重新获取文件列表
    // await this.getFileListById()
    // 导出此次保存文件
    const image = new Image()
    image.src = src
    const url = image.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream') // 输出类型
    const a = document.createElement('a') // 随便创建一个元素
    a.download = filename // 设置下载的文件名，默认是'下载'
    a.href = url
    document.body.appendChild(a)
    a.click()
    a.remove() // 下载之后把创建的元素删除
  })
}
